import 'package:cached_network_image/cached_network_image.dart';
import 'package:easydubbing/tencentPlayer/full_video_page.dart';
import 'package:easydubbing/tencentPlayer/util/time_util.dart';
import 'package:easydubbing/utils/FutureDioToken.dart';
import 'package:easydubbing/utils/SpUtil.dart';
import 'package:easydubbing/utils/api.dart';
import 'package:easydubbing/utils/style.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tencentplayer/controller/tencent_player_controller.dart';
import 'package:flutter_tencentplayer/model/player_config.dart';
import 'package:flutter_tencentplayer/view/tencent_player.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:loading_indicator_view/loading_indicator_view.dart';

import '../main.dart';

class IndexListItem extends StatefulWidget{
  final Map data;
  final bool isInView;
  final bool isFirstIn;
  final callBack;
  final numChange;

  const IndexListItem({Key key, this.isInView, this.data, this.callBack, this.isFirstIn, this.numChange}) : super(key: key);
  _IndexListItemState createState() => _IndexListItemState();
}
class _IndexListItemState extends State<IndexListItem>{
  TencentPlayerController player;
  VoidCallback listener;
  bool isInView;
  bool _controllerWasPlaying = false;
  Duration seekPos;
  bool showSeekText = false;
  bool isPlaying = false;
  bool notShowCover = false;
  bool isShowFast = false;
  TextEditingController commentController;
  FocusNode commentNode;
  Map data;
  bool isPlayed = false;
  bool myApplaud;
  bool myFavor;
  bool hasTouched = false;
  int uid;
  int isEssence;
  bool isLoading = false;

  @override
  void initState() {
    commentNode = new FocusNode();
    uid = SpUtil.sharedPreferences.getInt("uid");
    if(widget.isFirstIn)
      isInView = true;
    else isInView = widget.isInView;
    data = widget.data;
    isEssence = data["isessence"];
    myApplaud = data["myApplaud"]==null?false:true;
    myFavor = data["myFavor"]==null?false:true;
    commentController = new TextEditingController();
    player = TencentPlayerController.network(
        data["url"],
    playerConfig: PlayerConfig(autoPlay: false)
    )
    ;
    listener = () {
      if (!mounted) {
        return;
      }
      setState(() {});
    };
    player.addListener(listener);
    super.initState();
  }

  void seekToAbsolutePosition(Offset delta) {
    if (seekPos == null) return;
    if (mounted) setState(() {
      seekPos += Duration(milliseconds: 800) * delta.dx;
      if (seekPos < Duration()) {
        seekPos = Duration();
      } else if (seekPos > player.value.duration) {
        seekPos = player.value.duration;
      }
    });
  }

  @override
  void didUpdateWidget(covariant IndexListItem oldWidget) {
    if(oldWidget.isInView!=widget.isInView){
      setState(() {
        if(player.value.isPlaying)
        player.pause();
        isPlaying = false;
        if(widget.isFirstIn)
          widget.callBack();
        this.isInView = widget.isInView;
      });
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    Duration showDuration = seekPos != null ? seekPos : player.value.position;
    return Container(
      height: 440,
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                height: 45,
                width: 45,
                margin: EdgeInsets.only(left: 20),
                child: ClipOval(
                  child: Container(
                    child: CachedNetworkImage(
                      imageUrl: data["avatar"],
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 10,left: 10),
                child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Container(
                        width: 25,
                        height: 13,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(3)),
                          gradient: LinearGradient(
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                            colors: [
                              Color(0xFFF8C26A),
                              Color(0xFFFFDB7D),
                            ],
                          ),
                        ),
                        alignment: Alignment.center,
                        child: Text("PRO",style: TextStyle(color: Color(0xFF825C23),fontSize: 11,fontWeight: FontWeight.bold),),
                      ),
                      Container(
                        width: 13,
                        height: 13,
                        margin: EdgeInsets.only(left: 2,right: 3),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(3)),
                            color: Colors.red
                        ),
                        alignment: Alignment.center,
                        child: Text("V",style: TextStyle(color: Colors.white,fontSize: 11,fontWeight: FontWeight.bold),),
                      ),
                      Container(
                        child: Text(
                          "${data["alias"]}",style: TextStyle(color: Colors.grey,fontWeight: FontWeight.w600),
                        ),
                      )
                    ],
                  ),
                  Container(
                    width: 180,
                    height: 30,
                    margin: EdgeInsets.only(top: 5),
                    child: Text(
                      "${data["title"]}",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600),
                      maxLines: 2,
                    ),
                  )
                ],
              ),
              ),
              Spacer(),
              Container(
                child: Icon(Icons.add,color: Colors.red,),
              ),
              Container(
                margin: EdgeInsets.only(right: 30),
                child: Text(
                  "关注",style: TextStyle(color: Colors.red,fontWeight: FontWeight.w600),
                ),
              )
            ],
          ),
          Stack(
            children: [
              Container(
                height: 210,
                margin: EdgeInsets.only(left: 10,right: 10),
                child: Center(
                  child: AspectRatio(
                    aspectRatio: player.value.initialized?player.value.aspectRatio:1.8,
                    child: TencentPlayer(
                        player
                    ),
                  ),
                ),
              ),
              !player.value.initialized?Container(
                height: 210,
                alignment: Alignment.center,
                margin: EdgeInsets.only(left: 10,right: 10,bottom: 10),
                child: CachedNetworkImage(imageUrl: data["cover"],),
              ):SizedBox(),
              !isPlaying&&!isLoading?Container(
                margin: EdgeInsets.only(top: 90),
                alignment: Alignment.center,
                child: ClipOval(
                  child: Container(
                    height: 45,
                    width: 45,
                    color: Color(0x6f000000),
                    padding: EdgeInsets.only(left: 3),
                    child: Icon(Icons.play_arrow_rounded,size: 35,color: Colors.white,),
                  ),
                ),
              ): SizedBox(),
              isShowFast?Container(
                margin: EdgeInsets.only(left: 10,right: 10,top: 90),
                alignment: Alignment.centerRight,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Icon(Icons.fast_forward,color: Color(0x70FFFFFF),),
                    Text("x2",style: TextStyle(color: Color(0x70FFFFFF)),)
                  ],
                ),
              ):Container(),
              showSeekText ? Center(
                child: Padding(
                  padding: EdgeInsets.only(bottom: MediaQuery.of(context).size.width / 3),
                  child: Container(
                    width: 150,
                    height: 50,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: Color(0x7f000000),
                      borderRadius: BorderRadius.all(Radius.circular(10.0)),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        Text(TimeUtil.formatDuration(showDuration), style: TextStyle(
                          color: ProjectColor.mainColor,
                          fontSize: 18,
                        ),),
                        Text('/' + TimeUtil.formatDuration(player.value.duration), style: TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                        ),),
                      ],
                    ),
                  ),
                ),
              ): SizedBox(),
              isLoading?Container(
                height: 210,
                alignment: Alignment.center,
                padding: EdgeInsets.only(top: 15),
                child: Container(
                  height: 50,
                  width: 65,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Color(0x6f000000),
                      borderRadius: BorderRadius.all(Radius.circular(10))
                  ),
                  child: LineScalePulseOutIndicator(
                    lineColor: Colors.white,
                  ),
                ),
              ):SizedBox(),
              Container(
                height: 210,
                child: GestureDetector(
                  onDoubleTap: ()async {
                    if(!isInView)
                      return;
                    TencentPlayerController newController = await Navigator.of(context).push(
                        MaterialPageRoute(
                            builder: (_) =>
                                FullVideoPage(
                                  isInView: widget.isInView,
                                  rotation: 0,
                                  aspectRatio:player.value.aspectRatio,
                                  controller: player,
                                  playType: PlayType.network,
                                  showClearBtn: false,
                                ),
                            fullscreenDialog: true
                        )
                    );
                    if(mounted)
                      setState(() {
                        player = newController;
                      });
                  },
                  onHorizontalDragStart: (DragStartDetails details) {
                    if(!isInView)
                      return;
                  if (!player.value.initialized) {
                    return;
                  }
                  _controllerWasPlaying = player.value.isPlaying;
                  if (_controllerWasPlaying) {
                    player.pause();
                  }
                  setState(() {
                    seekPos = player.value.position;
                    showSeekText = true;
                  });
                },
                  onHorizontalDragUpdate: (DragUpdateDetails details) {
                    if(!isInView)
                      return;
                    if (!player.value.initialized) {
                      return;
                    }
                    seekToAbsolutePosition(details.delta);
                  },
                  onHorizontalDragEnd: (DragEndDetails details) async {
                    if(!isInView)
                      return;
                    await player.seekTo(seekPos);
                    seekPos = null;
                    if (_controllerWasPlaying) {
                      player.play();
                    }
                    setState(() {
                      showSeekText = false;
                    });
                  },
                  onTap: (){
                    if(!isInView)
                      return;
                    if(!isPlayed&&!hasTouched){
                      hasTouched = true;
                      FutureDio("get", Api.changeNum, {
                        "vid":data["vid"],
                        "field":"play",
                        "type":1,
                        "uid":uid??1
                      }).then((value){
                        setState(() {
                          hasTouched = false;
                          data["play"]++;
                          widget.numChange(data["comment"],data["applaud"],
                              data["play"],data["myApplaud"],data["myFavor"]);
                          isPlayed = true;
                        });
                      });
                    }
                    if(!player.value.initialized){
                      setState(() {
                        isLoading = true;
                      });
                      player.initialize().then((value) {
                        setState(() {{
                          player.play();
                          isPlaying = true;
                          isLoading = false;
                        }
                        });
                      });
                      return;
                    }
                    if(player.value.isPlaying){
                      setState(() {
                        isPlaying = false;
                        player.pause();
                      });
                    }
                    else
                      setState(() {
                        isPlaying = true;
                        notShowCover = true;
                        player.play();
                      });
                  },
                  onLongPress: (){
                    if(!isInView)
                      return;
                    player.setRate(2.0);
                    setState(() {
                      isShowFast = true;
                    });
                  },
                  onLongPressEnd: (e){
                    if(!isInView)
                      return;
                    player.setRate(1.0);
                    setState(() {
                      isShowFast = false;
                    });
                  },
                ),
              ),
            ],
          ),
          Container(
            margin: EdgeInsets.only(left: 10,bottom: 5),
            child: Text("${data["desc"]}",maxLines: 2,overflow: TextOverflow.ellipsis,style: TextStyle(color: Colors.grey,fontSize: 15),),
          ),
          Container(
            margin: EdgeInsets.only(left: 10),
            child: Row(
              children: [
                InkWell(
                  onTap:() {
                    if (uid == null) {
                      Fluttertoast.showToast(
                          msg: '请登录！',
                          toastLength: Toast.LENGTH_SHORT,
                          gravity: ToastGravity.BOTTOM,
                          backgroundColor: Colors.black38,
                          textColor: Colors.white,
                          fontSize: 16.0
                      );
                      return;
                    }
                    if (!hasTouched) {
                      hasTouched = true;
                      FutureDio("get", Api.changeNum, {
                        "vid": data["vid"],
                        "field": "applaud",
                        "type": !myApplaud ? 1 : 2,
                        "uid": uid ?? 1
                      }).then((value) {
                        setState(() {
                          hasTouched = false;
                          !myApplaud ? data["applaud"]++ : data["applaud"]--;
                          !myApplaud
                              ? data["myApplaud"] = 1
                              : data["myApplaud"] = null;
                          myApplaud = !myApplaud;
                          widget.numChange(data["comment"], data["applaud"],
                              data["play"], data["myApplaud"], data["myFavor"]);
                        });
                      });
                    }
                  },
                  child: Container(
                    height: 23,
                    child: Image.asset(myApplaud?"assets/icons/like-active.png":"assets/icons/like.png"),
                  ),
                ),
                Spacer(),
                InkWell(onTap:() {
                  if (uid == null) {
                    Fluttertoast.showToast(
                        msg: '请登录！',
                        toastLength: Toast.LENGTH_SHORT,
                        gravity: ToastGravity.BOTTOM,
                        backgroundColor: Colors.black38,
                        textColor: Colors.white,
                        fontSize: 16.0
                    );
                    return;
                  }
                  if (!hasTouched) {
                    hasTouched = true;
                    FutureDio("get", Api.changeNum, {
                      "vid": data["vid"],
                      "field": "favor",
                      "type": !myFavor ? 1 : 2,
                      "uid": uid ?? 1
                    }).then((value) {
                      setState(() {
                        hasTouched = false;
                        !myFavor
                            ? data["myFavor"] = 1
                            : data["myFavor"] = null;
                        myFavor = !myFavor;
                        Fluttertoast.showToast(
                            msg: !myFavor?"已取消收藏":'已收藏',
                            toastLength: Toast.LENGTH_SHORT,
                            gravity: ToastGravity.BOTTOM,
                            backgroundColor: Colors.black38,
                            textColor: Colors.white,
                            fontSize: 16.0
                        );
                        widget.numChange(data["comment"], data["applaud"],
                            data["play"], data["myApplaud"], data["myFavor"]);
                      });
                    });
                  }
                },
                  child: Container(
                    height: 23,
                    child: Image.asset(myFavor?"assets/icons/favor-full.png":"assets/icons/favor.png"),
                  ),
                ),
                Spacer(),
                Container(
                  height: 23,
                  child: Image.asset("assets/icons/share.png"),
                ),
                Spacer(),
                Container(
                  width: 150,
                  height: 40,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Color(0xFFF8F8F8),
                      borderRadius: BorderRadius.all(Radius.circular(10))
                  ),
                  padding: EdgeInsets.only(left: 10),
                  margin: EdgeInsets.only(right: 10),
                  child: TextField(
                    cursorColor: Color(0xFFBBBBBB),
                    cursorWidth: 1,
                    controller: commentController,
                    maxLines: 1,
                    focusNode: commentNode,
                    style: TextStyle(color: Colors.black),
                    decoration: InputDecoration(
                      hintText: '说些什么吧',
                      hintStyle: TextStyle(color: Color(0xFFbbbbbb)),
                      border: InputBorder.none,
                    ),
                  ),
                ),
                InkWell(
                  onTap: (){
                    if(commentController.value.text==""){
                      Fluttertoast.showToast(
                          msg: '请输入内容！',
                          toastLength: Toast.LENGTH_SHORT,
                          gravity: ToastGravity.BOTTOM,
                          backgroundColor: Colors.black38,
                          textColor: Colors.white,
                          fontSize: 16.0
                      );
                      return;
                    }
                    if(!hasTouched) {
                      hasTouched = true;
                      FutureDio("get", Api.sendComment, {
                        "vid": data["vid"],
                        "uid": uid,
                        "comment": commentController.value.text
                      }).then((value) {
                        Fluttertoast.showToast(
                            msg: '已发送评论',
                            toastLength: Toast.LENGTH_SHORT,
                            gravity: ToastGravity.BOTTOM,
                            backgroundColor: Colors.black38,
                            textColor: Colors.white,
                            fontSize: 16.0
                        );
                        hasTouched = false;
                        data["comment"]++;
                        if(commentNode.hasFocus){
                          commentNode.unfocus();
                        }
                        commentController.text = "";
                        widget.numChange(data["comment"],data["applaud"],
                            data["play"],data["myApplaud"],data["myFavor"]);
                      });
                    }
                  },
                  child: Container(
                    height: 30,
                    width: 50,
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(right: 10),
                    padding: EdgeInsets.only(left: 5,right: 5),
                    decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: [
                            ProjectColor.deepColor,
                            ProjectColor.mainColor,
                          ],
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(5))
                    ),
                    child: Text("发送",style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),),
                  ),
                ),
              ],
            ),
          ),
          Row(
            children: [
              Container(
                margin: EdgeInsets.only(left: 10,top: 10),
                child: Text("${data["applaud"]}点赞 · ${data["play"]}观看",style: TextStyle(color: Colors.grey,fontWeight: FontWeight.bold),),
              ),
              Spacer(),
              InkWell(
                onTap: (){
                  showModalBottomSheet(
                      context: context,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(20),
                          topRight: Radius.circular(20),
                        ),
                      ),
                      builder: (BuildContext context){
                        Future loadComment = FutureDio("get", Api.commentList, {
                              "vid":data["vid"]
                            });
                        return FutureBuilder(
                            future: loadComment,
                            builder: (BuildContext buildContext,AsyncSnapshot snapshot){
                              if(snapshot.connectionState == ConnectionState.done){
                                print(snapshot);
                                List commentList = snapshot.data.data["data"];
                                return Column(
                                  children: [
                                    Container(
                                      margin:EdgeInsets.only(top: 10),
                                      child: Text("评论(${data["comment"]})",style: TextStyle(
                                        fontWeight: FontWeight.bold,fontSize: 16
                                      ),),
                                    ),
                                    Expanded(
                                        child: ListView.builder(
                                        itemCount: commentList.length,
                                        itemBuilder: (context,index){
                                          return Container(
                                            margin: EdgeInsets.only(top: 10),
                                            child: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                Row(
                                                  children: [
                                                    Container(
                                                      height: 35,
                                                      width: 35,
                                                      margin: EdgeInsets.only(left:10),
                                                      child: ClipOval(
                                                        child: Container(
                                                          child: CachedNetworkImage(
                                                            imageUrl: commentList[index]["avatar"],
                                                            fit: BoxFit.cover,
                                                          ),
                                                        ),
                                                      ),
                                                    ),
                                                    SizedBox(width: 5,),
                                                    Text("${commentList[index]["alias"]}",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 15),),
                                                    Spacer(),
                                                    Text("${commentList[index]["createtime"]}",style: TextStyle(color: Colors.grey)),
                                                    SizedBox(width: 20,)
                                                  ],
                                                ),
                                                Container(
                                                  margin:EdgeInsets.only(top: 5,left: 20),
                                                  child: Text("${commentList[index]["comment"]}",style: TextStyle(fontSize: 16)),
                                                )
                                              ],
                                            ),
                                          );
                                        })
                                    )
                                  ],
                                );
                              }
                              return Center(
                                child: Container(
                                  width: 50,
                                  height: 50,
                                  child: LineSpinFadeLoaderIndicator(
                                    ballColor: ProjectColor.mainColor,
                                  ),
                                ),
                              );
                            });
                      });
                },
                child: Container(
                  height: 25,
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(right: 10,top: 10),
                  padding: EdgeInsets.only(left: 5,right: 5),
                  decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [
                          ProjectColor.deepColor,
                          ProjectColor.mainColor,
                        ],
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(5))
                  ),
                  child: Text("查看评论(${data["comment"]})",style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),),
                ),
              ),
            ],
          ),
          SizedBox(height: 10,),
          Container(
            margin: EdgeInsets.only(left: 10),
            child: Row(
              children: [
                isEssence==1?Container(
                  child: Icon(Icons.star_rounded,color: Colors.red,size: 18,),
                ):SizedBox(),
                isEssence==1?Container(
                  child: Text("精选",style: TextStyle(color: Colors.red,fontWeight: FontWeight.bold),),
                ):SizedBox(),
                isEssence==1?Container(
                  margin: EdgeInsets.only(left: 10),
                  child: Text("|",style: TextStyle(color: Color(0xFFF8F8F8),fontWeight: FontWeight.bold),),
                ):SizedBox(),
                Container(
                  margin: EdgeInsets.only(left: isEssence==1?10:0),
                  child: Text("来自频道",style: TextStyle(color: Colors.grey,fontWeight: FontWeight.bold),),
                ),
                Container(
                  margin: EdgeInsets.only(left: 10),
                  child: Icon(Icons.label,color: Colors.red,size: 18,),
                ),
                Container(
                  child: Text("${data["channel"]}",style: TextStyle(color: Colors.red,fontWeight: FontWeight.bold),),
                ),
                Spacer(),
                Container(
                  child: Text("${data["uploadtime"]}",style: TextStyle(color: Colors.grey,fontSize: 12),),
                ),
                SizedBox(width: 10,)
              ],
            ),
          ),
          SizedBox(height: 10,),
          Divider(color: Color(0xFFF8F8F8),thickness: 2,indent: 20,endIndent: 20,)
        ],
      ),
    );
  }

  @override
  void dispose() {
    player.dispose();
    super.dispose();
  }
}